package com.mszlu.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mszlu.blog.dao.dos.Archives;
import com.mszlu.blog.dao.mapper.ArticleBodyMapper;
import com.mszlu.blog.dao.mapper.ArticleMapper;
import com.mszlu.blog.dao.mapper.ArticleTagMapper;
import com.mszlu.blog.dao.mapper.CategoryMapper;
import com.mszlu.blog.dao.pojo.*;
import com.mszlu.blog.service.*;
import com.mszlu.blog.utils.UserThreadLocal;
import com.mszlu.blog.vo.*;
import com.mszlu.blog.vo.params.ArticleParam;
import com.mszlu.blog.vo.params.PageParams;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private TagsService tagService;
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ArticleTagMapper articleTagMapper;

    @Override
    public Result listArticle(PageParams pageParams){
        Page<Article> page = new Page<>(pageParams.getPage(),pageParams.getPageSize());

        IPage<Article> articleIPage = articleMapper.listArticle(page,
                pageParams.getCategoryId(),
                pageParams.getTagId(),
                pageParams.getYear(),
                pageParams.getMonth());
        List<Article> records = articleIPage.getRecords();

        return Result.success(copyList(records,true,true));
    }


//    @Override
//    public Result listArticle(PageParams pageParams) {
//       //分页查询article数据库表
//        Page<Article> page = new Page<>(pageParams.getPage(),pageParams.getPageSize());
//        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
//
//        if (pageParams.getCategoryId()!=null){
//            //and category_id=#{categoryId}
//            queryWrapper.eq(Article::getCategoryId,pageParams.getCategoryId());
//        }
//        List<Long> articleIdList = new ArrayList<>();
//        if (pageParams.getTagId()!=null){
//            //加入标签 条件查询
//            //article表中没有TagId字段？ 文章有多个标签
//            //article_tag     article_id  1:n   tag_id
//            LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            articleTagLambdaQueryWrapper.eq(ArticleTag::getTagId,pageParams.getTagId());
//            List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagLambdaQueryWrapper);
//            for (ArticleTag articleTag :articleTags){
//                articleIdList.add(articleTag.getArticleId());
//            }
//            if (articleIdList.size()>0){
//                //add id in(1,2,3...)
//                queryWrapper.in(Article::getId,articleIdList);
//            }
//        }
//        //1.是否置顶进行排序
//        //2.order by create_data desc
//        queryWrapper.orderByDesc(Article::getCreateDate, Article::getWeight);
//        Page<Article> articlesPage = articleMapper.selectPage(page,queryWrapper);
//        List<Article> records = articlesPage.getRecords();
//        //能直接返回吗？不能
//        List<ArticlesVo> articlesVoList = copyList(records,true,true);
//        return Result.success(articlesVoList);
//
//    }

    @Override
    public Result hotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts);
        queryWrapper.select(Article::getId,Article::getTitle);
        queryWrapper.last("limit "+limit);
        //select id ,title from article order by view_counts desc limit 5
        List<Article> articles =articleMapper.selectList(queryWrapper);

        return Result.success(copyList(articles,false,false));
    }

    /**
     * 最新文章
     * @param limit
     * @return
     */
    @Override
    public Result newArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.select(Article::getId,Article::getTitle);
        queryWrapper.last("limit "+limit);
        //select id ,title from article order by create_date desc limit 5
        List<Article> articles =articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles,false,false));

    }
//文章归档
    @Override
    public Result listArchives(int limit) {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);

    }
    @Autowired
    private ThreadService threadService;
    @Override
    public Result findArticleId(Long articleId) {
        /**
         * 1.根据id查询文章信息
         * 2.根据Body Id和categoryId 去做关联查询
         */

        Article article = this.articleMapper.selectById(articleId);
        ArticlesVo articlesVo = copy(article, true, true,true,true);
        //线程池实现点击量
        //可以把更新操纵扔到线程池中执行，就和主线程不相关了
        threadService.updateArticleViewCount(articleMapper,article);
        return Result.success(articlesVo);
    }

    @Override
    public Result publish(ArticleParam articleParam) {
        //此接口要加入到登录拦截中
        SysUser sysUser = UserThreadLocal.get();
        /**
         * 1.发布文章，构建Article对象
         * 2.作者id 为当前登录用户
         * 3.标签  要将标签加入到关联列表中
         * 4.body 内容存储
         */
        Article article = new Article();

        article.setAuthorId(sysUser.getId());
        article.setWeight(Article.Article_Common);
        article.setViewCounts(0);
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCommentCounts(0);
        article.setCreateDate(System.currentTimeMillis());
        article.setCategoryId(Long.parseLong(articleParam.getCategory().getId()));

        //插入文章Id，会生成一个id
        this.articleMapper.insert(article);
        //tags
        List<TagVo> tags = articleParam.getTags();
        if(tags!=null){
            Long articleId = Long.valueOf(article.getId());
            //加入关联列表
            for (TagVo tag: tags) {
                ArticleTag articleTag = new ArticleTag();
                articleTag.setTagId(Long.parseLong(tag.getId()));
                articleTag.setArticleId(articleId);
                articleTagMapper.insert(articleTag);
            }
        }
        //body内容存储
        ArticleBody articleBody = new ArticleBody();
        articleBody.setArticleId(Long.parseLong(article.getId()));
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.insert(articleBody);

        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);

        Map<String ,String > map = new HashMap<>();
        map.put("id",article.getId().toString());

        return Result.success(map);
    }

    private List<ArticlesVo>copyList(List<Article> records,boolean isTag,boolean isAuthor){
        List<ArticlesVo> articlesVoList = new ArrayList<>();
        for (Article record : records) {
            articlesVoList.add(copy(record,isTag,isAuthor,false,false));
        }
        return articlesVoList;
    }
    private List<ArticlesVo>copyList(List<Article> records,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory){
        List<ArticlesVo> articlesVoList = new ArrayList<>();
        for (Article record : records) {
            articlesVoList.add(copy(record,isTag,isAuthor,isBody,isCategory));
        }
        return articlesVoList;
    }
    @Autowired
    private CategoryService categoryService;
    private ArticlesVo copy(Article article,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory){
        ArticlesVo articlesVo = new ArticlesVo();
        articlesVo.setId(String.valueOf(article.getId()));
        BeanUtils.copyProperties(article,articlesVo);

        articlesVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        //并不是所有的接口 都需要标签，作者信息
        if(isTag){
            Long articaleId = Long.parseLong(article.getId());
            articlesVo.setTags(tagService.findTagsByArticleId(articaleId));
        }
        if (isAuthor){
            Long authorId = article.getAuthorId();
            articlesVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }
        if (isBody){
            Long bodyId = article.getBodyId();
            articlesVo.setBody(findArticleBodyIdById(bodyId));
        }
        if(isCategory){
            Long categoryId =article.getCategoryId();
            articlesVo.setCategorys(categoryService.findCategoryById(categoryId));
        }



        return articlesVo;
    }


    @Autowired
    private ArticleBodyMapper articleBodyMapper;
    private ArticleBodyVo findArticleBodyIdById(Long bodyId) {
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);
        ArticleBodyVo articleBodyVo =new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());

        return articleBodyVo;

    }
}
